import axios from 'axios'
import { Message } from 'element-ui'
// import {
//   notification
// } from 'ant-design-vue'
/* eslint-disable */
/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams (params) {
  let result = ''
  Object.keys(params).forEach((key) => {
    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
      result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
    }
  })
  return result
}
axios.defaults.headers['content-type'] = 'application/json;'
axios.defaults.headers['x-requested-with'] = 'XMLHttpRequest'
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000
})

const repeatToken = ''
// request拦截器
service.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer ' + sessionStorage.getItem('token') // 让每个请求携带自定义token 请根据实际情况自行修改
  config.headers.repeatToken = repeatToken + ':' + config.url
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      let value = ''
      if (typeof (config.params[propName]) == "string") {
        value = config.params[propName].trim();
      } else {
        value = config.params[propName];
      }
      var part = encodeURIComponent(propName) + "="
      if (value && typeof (value) !== 'undefined') {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  } else if (config.method === 'post' && config.data) {
    if (typeof (config.data) === 'object') {
      for (const propName of Object.keys(config.data)) {
        if (config.data[propName]) {
          if (typeof (config.data[propName]) == "string") {
            config.data[propName] = config.data[propName].trim();
          }
        }
      }
    }
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    if (code !== 200) {
      Message.error(res.data.message.join())
    }
    return res.data
  },
  error => {
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename) {
  return service.post(url, params, {
    transformRequest: [(params) => {
      return tansParams(params)
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'blob'
  }).then((data) => {
    const content = data
    const blob = new Blob([content])
    if ('download' in document.createElement('a')) {
      const elink = document.createElement('a')
      elink.download = filename
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    } else {
      navigator.msSaveBlob(blob, filename)
    }
  }).catch((r) => {
    console.error(r)
  })
}

export default service
